package com.trumeen.immichgallery.ui.screen

import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.trumeen.immichgallery.model.ImageSwitchPeriod
import com.trumeen.immichgallery.model.ImageType
import com.trumeen.immichgallery.ui.components.ServerStatusIndicator
import com.trumeen.immichgallery.viewmodel.ConnectionStatus
import com.trumeen.immichgallery.viewmodel.SettingsViewModel
import kotlinx.coroutines.launch
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import com.trumeen.immichgallery.ui.navigation.Screen

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(
    navController: NavController,
    viewModel: SettingsViewModel = hiltViewModel()
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    val serverAddress by viewModel.serverAddress.collectAsState()
    val username by viewModel.username.collectAsState()
    val password by viewModel.password.collectAsState()
    val isAuthenticated by viewModel.isAuthenticated.collectAsState()
    val isConnecting by viewModel.isConnecting.collectAsState()
    val imageSwitchPeriod by viewModel.imageSwitchPeriod.collectAsState()
    val imageType by viewModel.imageType.collectAsState()
    val selectedPersonId by viewModel.selectedPersonId.collectAsState()


    LaunchedEffect(isAuthenticated) {
        if (isAuthenticated) {
            Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show()
            navController.popBackStack()
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("设置") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                    }
                }
            )
        }
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .padding(innerPadding)
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 服务器设置
            ServerSettingsCard(
                serverAddress = serverAddress,
                username = username,
                password = password,
                isAuthenticated = isAuthenticated,
                isConnecting = isConnecting,
                onServerAddressChange = { viewModel.updateServerAddress(it) },
                onUsernameChange = { viewModel.updateUsername(it) },
                onPasswordChange = { viewModel.updatePassword(it) },
                onTestConnection = {
                    scope.launch {
                        viewModel.testConnection()
                        Toast.makeText(context, "测试连接请求已发送", Toast.LENGTH_SHORT).show()
                    }
                },
                onLogin = {
                    scope.launch {
                        viewModel.login()
                        Toast.makeText(context, "登录请求已发送", Toast.LENGTH_SHORT).show()
                    }
                },
                onLogout = {
                    scope.launch {
                        viewModel.logout()
                        Toast.makeText(context, "已登出", Toast.LENGTH_SHORT).show()
                    }
                }
            )

            // 图片切换周期设置
            ImageSwitchPeriodCard(
                selectedPeriod = imageSwitchPeriod,
                onPeriodSelected = { viewModel.updateImageSwitchPeriod(it) }
            )

            // 图片类型设置
            ImageTypeCard(
                selectedType = imageType,
                onTypeSelected = {
                    viewModel.updateImageType(it)
                    if (it == ImageType.SPECIFIC_PERSON) {
                        navController.navigate(Screen.PersonSelection)
                    }
                }
            )

            // 保存设置按钮
            Button(
                onClick = {
                    scope.launch {
                        viewModel.saveSettings()
                        Toast.makeText(context, "设置已保存", Toast.LENGTH_SHORT).show()
                        navController.popBackStack()
                    }
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(56.dp),
                enabled = !isConnecting
            ) {
                Text("保存设置")
            }
        }
    }
}

@Composable
private fun ServerSettingsCard(
    serverAddress: String,
    username: String,
    password: String,
    isAuthenticated: Boolean,
    isConnecting: Boolean,
    onServerAddressChange: (String) -> Unit,
    onUsernameChange: (String) -> Unit,
    onPasswordChange: (String) -> Unit,
    onTestConnection: () -> Unit,
    onLogin: () -> Unit,
    onLogout: () -> Unit
) {
    Card {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = "服务器设置",
                style = MaterialTheme.typography.headlineSmall,
                modifier = Modifier.padding(bottom = 16.dp)
            )

            // 服务器地址
            OutlinedTextField(
                value = serverAddress,
                onValueChange = onServerAddressChange,
                label = { Text("服务器地址") },
                modifier = Modifier.fillMaxWidth(),
                placeholder = { Text("http://192.168.3.18:2283/api") },
                enabled = !isConnecting
            )

            Spacer(modifier = Modifier.height(12.dp))

            // 用户名
            OutlinedTextField(
                value = username,
                onValueChange = onUsernameChange,
                label = { Text("201888400@qq.com") },
                modifier = Modifier.fillMaxWidth(),
                enabled = !isConnecting && !isAuthenticated
            )

            Spacer(modifier = Modifier.height(12.dp))

            // 密码
            if (!isAuthenticated) {
                OutlinedTextField(
                    value = password,
                    onValueChange = onPasswordChange,
                    label = { Text("密码") },
                    modifier = Modifier.fillMaxWidth(),
                    visualTransformation = PasswordVisualTransformation(),
                    enabled = !isConnecting
                )

                Spacer(modifier = Modifier.height(16.dp))
            }

            // 状态和操作按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 状态指示
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    ServerStatusIndicator(
                        status = if (isAuthenticated) ConnectionStatus.CONNECTED else ConnectionStatus.NOT_CONNECTED
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = if (isAuthenticated) "已连接" else "未连接",
                        style = MaterialTheme.typography.bodyMedium
                    )
                }

                // 操作按钮
                Row {
                    Button(
                        onClick = onTestConnection,
                        modifier = Modifier.padding(end = 8.dp),
                        enabled = serverAddress.isNotBlank() && !isConnecting
                    ) {
                        Text("测试连接")
                    }

                    Button(
                        onClick = if (isAuthenticated) onLogout else onLogin,
                        enabled = serverAddress.isNotBlank() &&
                                username.isNotBlank() &&
                                password.isNotBlank() &&
                                !isConnecting
                    ) {
                        if (isConnecting) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(16.dp),
                                strokeWidth = 2.dp,
                                color = MaterialTheme.colorScheme.onPrimary
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text("处理中...")
                        } else {
                            Text(if (isAuthenticated) "登出" else "登录")
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun ImageSwitchPeriodCard(
    selectedPeriod: ImageSwitchPeriod,
    onPeriodSelected: (ImageSwitchPeriod) -> Unit
) {
    Card {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = "图片切换周期",
                style = MaterialTheme.typography.headlineSmall,
                modifier = Modifier.padding(bottom = 16.dp)
            )

            ImageSwitchPeriod.values().forEach { period ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable { onPeriodSelected(period) },
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    RadioButton(
                        selected = selectedPeriod == period,
                        onClick = { onPeriodSelected(period) }
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = when (period) {
                            ImageSwitchPeriod.ONE_HOUR -> "1小时"
                            ImageSwitchPeriod.HALF_DAY -> "12小时"
                            ImageSwitchPeriod.ONE_DAY -> "24小时"
                        },
                        style = MaterialTheme.typography.bodyMedium
                    )
                }
            }
        }
    }
}

@Composable
private fun ImageTypeCard(
    selectedType: ImageType,
    onTypeSelected: (ImageType) -> Unit
) {
    Card {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = "显示图片类型",
                style = MaterialTheme.typography.headlineSmall,
                modifier = Modifier.padding(bottom = 16.dp)
            )

            ImageType.values().forEach { type ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable { onTypeSelected(type) },
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    RadioButton(
                        selected = selectedType == type,
                        onClick = { onTypeSelected(type) }
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = when (type) {
                            ImageType.LANDSCAPE -> "风景"
                            ImageType.SPECIFIC_PERSON -> "指定人物"
                            ImageType.TODAY_IN_HISTORY -> "那年今日"
                        },
                        style = MaterialTheme.typography.bodyMedium
                    )
                }
            }
        }
    }
}